<?php
class Zendvn_System_Acl {
	
	protected $_acl;
	
	protected $_role;
	
	protected $_ns;
	
	public function __construct(){
		$this->_acl = new Zend_Acl();
		$this->_ns = new Zend_Session_Namespace('info');
	}
	
	public function isAllowed($arrParam = null)
	{
		$this->_acl->addRole(new Zend_Acl_Role($this->_ns->acl['role']));
		$groupPrivileges = $this->_ns->acl['privileges'];
		$this->_acl->allow($this->_ns->acl['role'], null, $groupPrivileges);
		
		$privilege = $arrParam['module'] . '_' . $arrParam['controller'] . '_' . $arrParam['action']; 
		$flagAccess = false;
		if ($this->_acl->isAllowed($this->_ns->acl['role'], null, $privilege))
		{
			$flagAccess = true;
		}
		return $flagAccess;
	}
	
	public function createPrivilegeArray($opstions = null){
		$nsInfo = $this->_ns->getIterator();
		$info = $nsInfo['member'];
		$group_id = $info['group_id'];
		
		$cache = new Zendvn_Cache();
		if ( ! $result = $cache->load('privileges_' . $group_id))
		{
			$db = Zend_Registry::get('connectDb');
			$select = $db->select()
					->from('user_group_privileges as gp', array('p.module', 'p.controller', 'p.action'))
					->join('privileges as p', 'gp.privilege_id = p.id')
					->joinLeft('user_group as ug', 'ug.id = gp.group_id')
					->where('gp.status = 1 AND ug.status = 1')
					->where('gp.group_id = ?', $group_id, INTEGER);
			$result = $db->fetchAll($select);
			if ( ! empty($result))
			{
				$cache->save($result, 'privileges_' . $group_id);	
			}
			else
			{
				$ns = new Zend_Session_Namespace('Zend_Auth');
				$ns->unsetAll();
				echo 'locked';
			}
		}
		
		$arrPrivilages = array();
		if ( ! empty($result))
		{
			foreach ($result as $key)
			{
				$arrPrivilages[] = $key['module'] . '_' . $key['controller'] . '_' . $key['action'];
			}
		}	
		$this->_ns->acl['privileges'] = $arrPrivilages;
		return $result;
	}
	
	public function createRole($opstions = null)
	{
		$nsInfo = $this->_ns->getIterator();
		$info = $nsInfo['group'];
		$this->_ns->acl['role'] = $info['group_name'];
	}
}